#include "mcu_dda_server.h"

#include "bsp_usb.h"
#include "mcu_dda_usb_driver.h" 



#include "bsp_dda_usart.h" 
#include "mcu_dda_serialport_driver.h" 
#include "mcu_dda_modbus_driver.h" 







static McuDdaModBusDriver* g_mcuDdaModBusDriver = NULL;
static McuDdaDriverBase* ddaDriverBase = NULL;


void OnDdaUsbRecvCallBack(uint8_t *buf, uint32_t len,void* owner) {
	 if (ddaDriverBase == owner && ddaDriverBase->Import(buf, len)) {
		 ddaDriverBase->m_receiveListen->Post();
	 }
}


void OnDdaSerialportRecvCallBack(uint8_t* buf, uint32_t len) {
	if (ddaDriverBase->Import(buf, len)) {
		ddaDriverBase->m_receiveListen->Post();
	}
}


void OnDdaUartRecvCallBack(uint8_t* buf, uint32_t len) {

	if (g_mcuDdaModBusDriver->m_commDriver->Import(buf, len)) {
		g_mcuDdaModBusDriver->m_comDriverListen->Post();
	}
}





BOOL  DdaServerOpen(DdaServer_InitTypeDef * ddaServerInitStruct) {
	if (ddaServerInitStruct->ddaServerType == DDA_SERVER_TYPE_USB) {
		ddaDriverBase = new McuDdaUsbDriver();
		BspSetRecvCallBack(OnDdaUsbRecvCallBack, ddaDriverBase);
	}
	else if (ddaServerInitStruct->ddaServerType == DDA_SERVER_TYPE_SERIALPORT) {
		ddaDriverBase = new McuDdaSerialportDriver(
			 ddaServerInitStruct->comPort, 115200, ddaServerInitStruct->is485);
		BspDdaSetRecvCallBack(OnDdaSerialportRecvCallBack);
	}
	else if (ddaServerInitStruct->ddaServerType == DDA_SERVER_TYPE_MODBUS) {
		g_mcuDdaModBusDriver = new McuDdaModBusDriver(
			ddaServerInitStruct->comPort, 
			ddaServerInitStruct->slaveAddr,
			115200,
			ddaServerInitStruct->is485,
			ddaServerInitStruct->isLeader,
		  ddaServerInitStruct->teamCount
		);
		BspDdaSetRecvCallBack(OnDdaUartRecvCallBack);
	}
	return true;
}



BOOL  DdaServerPostGram(DWORD  buf[], DWORD  bufLen, DWORD unitLen) {

	return ddaDriverBase->PostGram(buf, bufLen, unitLen);
}

BOOL DdaServerPostEvent(WORD  instance, WORD  eventId, Ndata* eventArgs) {

	return ddaDriverBase->PostEvent(instance, eventId, eventArgs);
}


BOOL  DdaServerPostDataChangedEvent(WORD  instance, DataChangedEvent * dataChangeEvent) {
	NPack* eventArgs = new NPack();
	eventArgs->AppendDataBody(STR_TYPE, dataChangeEvent->member, 16);
	eventArgs->AppendMember(dataChangeEvent->value);
	eventArgs->AppendDataBody(STR_TYPE, dataChangeEvent->message, 16);
	BOOL r= DdaServerPostEvent(instance, EVENT_DataChanged, eventArgs);
	delete eventArgs;
	return r;
}